package com.songyz.image.compress.controller;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

import com.songyz.image.compress.utils.CompressUtils;

@Controller
public class WebSocketController {

    private static Logger logger = LoggerFactory.getLogger(WebSocketController.class);

    public static class WebSocketMessage {
        public String sessionId;
        public String content;

        @Override
        public String toString() {
            return "WebSocketMessage [sessionId=" + sessionId + ", content=" + content + "]";
        }

    }

    @Autowired
    public SimpMessagingTemplate template;

    @MessageMapping("/subscribe")
    public void subscribe(WebSocketMessage msg) {
        logger.info("进入方法subscribe,msg:{}", msg);
        // 广播使用convertAndSend方法，第一个参数为目的地，和js中订阅的目的地要一致
        // template.convertAndSend("/topic/getResponse", rm.getName());

    }

    @MessageMapping("/clearFile")
    public void queue(WebSocketMessage msg) throws IOException {
        logger.info("进入方法clearFile,msg:{}", msg);

        File file = new File(CompressUtils.getSessionPath(msg.sessionId));
        if (file.exists() && file.listFiles().length > 0) {
            Path path = Paths.get(file.getAbsolutePath());

            Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
                public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException {
                    Files.delete(file);
                    logger.info("删除缓存文件：{}", file);
                    return FileVisitResult.CONTINUE;
                }

                public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                    Files.delete(dir);
                    logger.info("删除缓存文件夹：{}", dir);
                    return FileVisitResult.CONTINUE;
                }
            });
        }

    }
}
